<?php

/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License, version 2, as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * @category  PayIntelligent
 * @package   PayIntelligent_ClickandBuy
 * @copyright (C) 2010 PayIntelligent GmbH  <http://www.payintelligent.de/>
 * @license   GPLv2
 */

require('includes/application_top.php');
$language= $_SESSION['language'];

include('../lang/'.$_SESSION['language'].'/admin/pi_clickandbuy.php');		

require(DIR_FS_CATALOG.DIR_WS_CLASSES.'class.clickandbuy.php');
$cab = new clickandbuy();			

$shopOrderID = $_GET['oID'];
!empty($_GET['externalID']) ? $externalID = $_GET['externalID'] : $externalID = substr(md5(uniqid(rand())),0,12);
!empty($_GET['intPlaces']) ? $intPlaces = $_GET['intPlaces'] : $intPlaces = '0';	
!empty($_GET['decPlaces']) ? $decPlaces = $_GET['decPlaces'] : $decPlaces = '00';	
!empty($_GET['actionSave']) ? $actionSave = true : $actionSave = false;	

if(!empty($_GET['itemDesc1'])) 
	$itemDesc1 = $_GET['itemDesc1'];

$authentication = $cab->getCabSettings('clickandbuy');

$postAmount = (float)$intPlaces.'.'.$decPlaces;

$cabOrderDetails = $db->db_query("SELECT * FROM ".DB_PREFIX."picab_orders WHERE shopOrderID ='".$shopOrderID."' ");

$amount = (float)$cabOrderDetails->fields['amount'] ;
$refunded = (float)$cabOrderDetails->fields['refunded'] + $postAmount;
$cancelled = (float)$cabOrderDetails->fields['cancelled'];
$openAmount = ($amount - $refunded - $cancelled);					

if ($amount == $cancelled) {
  $openAmount = 0;
	$refunded = (float)$cabOrderDetails->fields['refunded'];
  $messageBox = 'ERROR';
	$errorDescription = CLICKANDBUY_ORDER_REFUND_ERROR_MESSAGE_1;    	
} elseif ((($openAmount < 0) || ($amount < $refunded))) {
  $openAmount = 0;
  $refunded = (float)$cabOrderDetails->fields['refunded'];
	$messageBox = 'ERROR';
	$errorDescription = CLICKANDBUY_ORDER_REFUND_ERROR_MESSAGE_2;
}
  
$openAmount = number_format($openAmount, 2, '.', ''); 
$refunded = number_format($refunded, 2, '.', ''); 
			
$places = explode(".", $openAmount);
$intPlaces = $places[0];
$decPlaces = $places[1];
        
if(($actionSave) && empty($messageBox)) {						
	$items = array();
											
	$details['amount'] = $postAmount;
	$details['currency'] = $cabOrderDetails->fields['currency'];
	$details['transactionID']= $cabOrderDetails->fields['transactionID'];
	$details['externalID'] = $externalID;
	$items[1]['itemType'] = 'item1Text';	
	$items[1]['textItemDescription'] = $itemDesc1;
			
	$requestResult = $cab->refundRequest($authentication,$details,$items);
	$requestValues = $requestResult['values'];

	if ($requestValues['transaction']['transactionStatus'] == 'SUCCESS' OR $requestValues['transaction']['transactionStatus'] == 'IN_PROGRESS') {
		$db->db_query("UPDATE picab_orders SET refunded =  '".$refunded."' WHERE shopOrderID ='".$shopOrderID."'");
		$messageBox = 'SUCCESS';
		
		$transactionID = $requestValues['transaction']['transactionID'];
		$transactionStatus = $requestValues['transaction']['transactionStatus'];									
		$db->db_query("INSERT INTO ".DB_PREFIX."picab_transactions (id,shopOrderID,transactionID,externalID,transactionType,description,amount,currency,paid,status,created,modified) VALUES (NULL,'".$shopOrderID."','".$transactionID."','".$externalID."','refund','".$itemDesc1."',".$postAmount.",'".$cabOrderDetails->fields['currency']."',1,'".$transactionStatus."',NOW(),NOW())");
	} else {
		$intPlaces = $intPlaces;
		$decPlaces = $decPlaces;		
		$refunded = (float)$cabOrderDetails->fields['refunded'];									
		$messageBox = 'ERROR';
		$errorDescription = $requestResult['values']['detail']['errorDetails']['description'];
	}
}
?>
<table border="0" width="100%" cellspacing="0" cellpadding="2" height="40">
	<tr>
		<td class="pageHeading"><?php echo CLICKANDBUY_ORDER_CLICKANDBUY.' '.CLICKANDBUY_ORDER_DETAILS_REFUND; ?></td>
		<td class="pageHeading" align="right">
			<a class="button cab_button" href="pi_clickandbuy_details.php?oID=<?php echo $shopOrderID; ?>">
				<?php echo CLICKANDBUY_ORDER_DETAILS_BACK; ?>
			</a>
		</td>
	</tr>
</table>					
<?php 
	if ($messageBox == 'SUCCESS') {
		$showMessage = $cab->showMessageSuccess(CLICKANDBUY_ORDER_REFUND_SUCCESSFUL. ' ('.CLICKANDBUY_ORDER_DETAILS_CLICKANDBUY_STATUS.': '.$transactionStatus.').');
		echo '<div class="clickandbuy_msg">'.$showMessage.'</div>';
	} elseif ($messageBox == 'ERROR') {
		$showMessage = $cab->showMessageError(CLICKANDBUY_ORDER_REFUND_ERROR.' '.$errorDescription);
		echo '<div class="clickandbuy_msg">'.$showMessage.'</div>';
	}
?>									        
<table border="0" width="100%" cellspacing="0" cellpadding="2">
	<tr>
		<td>		
			<table cellspacing="0" cellpadding="5" border="0" width="98%">
				<tr>
					<td width="50%">
						<table cellspacing="0" cellpadding="5" border="0" width="400">
							<tr>
								<td valign="top" class="infoBoxHeading"colspan="2">
									<b><?php echo CLICKANDBUY_ORDER_DETAILS_REFUND; ?>: </b>
								</td>                      
							</tr>
							<tr>
								<td class="infoBoxContent" height="20"><?php echo CLICKANDBUY_ORDER_DETAILS_EXTERNALID; ?>:</td>
								<td class="infoBoxContent"><?php echo $externalID; ?></td>
							</tr>
							<tr>
								<td class="infoBoxContent" height="20" width="120"><?php echo CLICKANDBUY_ORDER_DETAILS_TOTAL_AMOUNT; ?>:</td>
								<td class="infoBoxContent"><?php echo $cabOrderDetails->fields['amount'].' '.$cabOrderDetails->fields['currency']; ?></td>
							</tr>
							<tr>
								<td class="infoBoxContent" height="20" width="120"><?php echo CLICKANDBUY_ORDER_DETAILS_REFUNDED; ?>:</td>
								<td class="infoBoxContent"><?php echo $refunded.' '.$cabOrderDetails->fields['currency']; ?></td>
							</tr>
							<tr>
								<td class="infoBoxContent" height="20" width="120"><?php echo CLICKANDBUY_ORDER_DETAILS_CANCELLED; ?>:</td>
								<td class="infoBoxContent"><?php echo $cabOrderDetails->fields['cancelled'].' '.$cabOrderDetails->fields['currency']; ?></td>
							</tr>
							<tr>
								<td class="infoBoxContent" height="20" width="120"><?php echo CLICKANDBUY_ORDER_DETAILS_AMOUNT; ?>:</td>
								<td class="infoBoxContent">
									<input name="intPlaces" type="text" value="<?php echo $intPlaces; ?>" size="3" maxlength="12"class="editinput intPlaces" />,
									<input name="decPlaces" type="text" value="<?php echo $decPlaces; ?>" size="2" maxlength="2"class="editinput decPlaces" /> <?php echo $cabOrderDetails->fields['currency']; ?>
							</tr>
							<tr>
								<td class="infoBoxContent" height="20" width="120"><?php echo CLICKANDBUY_ORDER_DETAILS_DESCRIPTION; ?>:</td>
								<td class="infoBoxContent">
									<input type="text" value="<?php echo $itemDesc1; ?>" name="itemDesc1" maxlength="255" size="25" class="editinput itemDesc1" />
								</td>
							</tr>
							<tr>
								<td class="infoBoxContent" height="20" width="120">&nbsp;</td>
								<td class="infoBoxContent">
									<a onclick="return getInputs()" class="button cab_button refund_href" href="">
										<?php echo CLICKANDBUY_ORDER_REFUND_REFUND_NOW; ?>
									</a>
									<script type="text/javascript">
										function getInputs() {
											var url = '<?php echo 'pi_clickandbuy_refund.php?oID='.$shopOrderID.'&actionSave=true&externalID='.$externalID; ?>';
											url += '&intPlaces='+$('.intPlaces').val();
											url += '&decPlaces='+$('.decPlaces').val();
											url += '&itemDesc1='+$('.itemDesc1').val();
											$('.refund_href').attr('href', url);
										}
									</script>
								</td>
							</tr>
						</table>
					</td>
				</tr>	
			</table>
		</td>
	</tr>
</table>		